package com.amading.socket;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amading.entity.ImMessage;
import com.amading.repository.ImMessageRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.util.*;

//public class MyWebSocketHandler  {
//
//}
@Slf4j
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private ImMessageRepository imMessageRepository;

    private Map<String, WebSocketSession> passengerList = new HashMap<>();
    private Map<String, WebSocketSession> driverList = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后的逻辑
        //获取连接参数，进行相关认证操作

        log.info("用户连接成功 " + session.getUri().getQuery());

        Map<String, String> params = getParams(session.getUri());
        String source = params.get("source");
        String token = params.get("token");
        String userId = params.get("user_id");

        boolean checkLogin = false;
        if ("1".equals(source)) {
            //乘客连接socket
            //进行token校验
            checkLogin = true;

        } else if ("2".equals(source)) {
            //司机连接socket
            //进行token校验
            checkLogin = true;

        } else {
            //非乘客  非司机  直接关闭此连接
            checkLogin = false;
            session.close();
        }

        if (checkLogin) {
            //如果确认用户身份通过后，则需要将此连接保存起来
            if ("1".equals(source)) {
                passengerList.put(userId, session);
            }
            if ("2".equals(source)) {
                driverList.put(userId, session);
            }
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Map<String, String> params = getParams(session.getUri());
        String source = params.get("source");
        String token = params.get("token");
        String userId = params.get("user_id");

        System.out.println(message.getPayload());

        //{"type":1,"content":"","orderId":""}
        //将收到的消息进行格式化
        if (StringUtils.isNotBlank(message.getPayload())) {
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(message.getPayload());
                Integer type = jsonObject.getInteger("type");
                if (type != null) {
                    //根据不同的type确定不同的操作内容
                    //获取我的未读消息数量，用于刚连接上socket，询问一下我是否有未读消息
                    if (type == 1) {
                        if ("1".equals(source)) {
                            //获取乘客的未读消息数量
                            //第一步，先查询乘客能进行对话的订单
                            //TODO
                            //此处直接模拟两个订单号 分别为order_id_1与order_id_2
                            String[] orderIds = {"order_id_1", "order_id_2"};

                            //第二步，查询每个订单下司机给我的未读消息数量
                            JSONArray jsonArray = new JSONArray();
                            for (String orderId : orderIds) {
                                Long unReadCount = imMessageRepository.countByIsReadAndSourceAndOrderId(0, 2, orderId);

                                JSONObject unReadJson = new JSONObject();
                                unReadJson.put("orderId", orderId);
                                unReadJson.put("unReadCount", unReadCount);
                                jsonArray.add(unReadJson);
                            }

                            //第三步，将数据返回回去
                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 1);
                            returnContent.put("data", jsonArray);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));
                        }

                        if ("2".equals(source)) {
                            //获取司机的未读消息数量
                            //第一步，先查询司机能进行对话的订单
                            //TODO
                            //此处直接模拟两个订单号 分别为order_id_1与order_id_2
                            String[] orderIds = {"order_id_1", "order_id_2"};

                            //第二步，查询每个订单下乘客给我的未读消息数量
                            JSONArray jsonArray = new JSONArray();
                            for (String orderId : orderIds) {
                                Long unReadCount = imMessageRepository.countByIsReadAndSourceAndOrderId(0, 1, orderId);

                                JSONObject unReadJson = new JSONObject();
                                unReadJson.put("orderId", orderId);
                                unReadJson.put("unReadCount", unReadCount);
                                jsonArray.add(unReadJson);
                            }

                            //第三步，将数据返回回去
                            //第三步，将数据返回回去
                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 1);
                            returnContent.put("data", jsonArray);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));
                        }
                    }

                    //根据订单ID获取此订单的所有消息
                    if (type == 2) {
                        String orderId = jsonObject.getString("orderId");
                        if ("1".equals(source)) {
                            List<ImMessage> imMessageList = imMessageRepository.findImMessagesByOrderIdOrderBySendTimeAsc(orderId);

                            //乘客获取信息，如果有乘客未读的司机信息，则需要将司机发过来的消息设置为已读
                            List<String> readIdList = new ArrayList<>();
                            for (ImMessage imMessage : imMessageList) {
                                if (imMessage.getSource().equals(2) && imMessage.getIsRead().equals(0)) {
                                    imMessage.setIsRead(1);
                                    imMessageRepository.save(imMessage);
                                    readIdList.add(imMessage.getIdMessage());
                                }
                            }

                            if (!readIdList.isEmpty()) {
                                //发送消息给司机，告知乘客已读消息了
                                //此处默认司机ID为sj_1  到Map中找到司机
                                //TODO
                                WebSocketSession driverSocket = driverList.get("sj_1");
                                //如果司机在线的话，则推送消息给司机
                                if (driverSocket != null) {
                                    JSONObject returnContent = new JSONObject();
                                    returnContent.put("type", 3);
                                    returnContent.put("orderId", orderId);
                                    returnContent.put("data", readIdList);
                                    driverSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                                }
                            }


                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 2);
                            returnContent.put("orderId", orderId);
                            returnContent.put("data", imMessageList);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));
                        }

                        if ("2".equals(source)) {
                            List<ImMessage> imMessageList = imMessageRepository.findImMessagesByOrderIdOrderBySendTimeAsc(orderId);

                            //司机获取信息，如果有司机未读的乘客信息，则需要将乘客发过来的消息设置为已读
                            List<String> readIdList = new ArrayList<>();
                            for (ImMessage imMessage : imMessageList) {
                                if (imMessage.getSource().equals(1) && imMessage.getIsRead().equals(0)) {
                                    imMessage.setIsRead(1);
                                    imMessageRepository.save(imMessage);
                                    readIdList.add(imMessage.getIdMessage());
                                }
                            }

                            if (!readIdList.isEmpty()) {
                                //发送消息给乘客，告知司机已读消息了
                                //此处默认乘客ID为ck_1  到Map中找到乘客
                                //TODO
                                WebSocketSession passengerSocket = passengerList.get("sj_1");
                                //如果乘客在线的话，则推送消息给乘客
                                if (passengerSocket != null) {
                                    JSONObject returnContent = new JSONObject();
                                    returnContent.put("type", 3);
                                    returnContent.put("orderId", orderId);
                                    returnContent.put("data", readIdList);
                                    passengerSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                                }
                            }


                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 2);
                            returnContent.put("orderId", orderId);
                            returnContent.put("data", imMessageList);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));
                        }
                    }

                    //乘客或司机当前已经在聊天窗口，发送已读消息事件
                    if (type == 3) {
                        String orderId = jsonObject.getString("orderId");

                        if ("1".equals(source)) {
                            JSONArray jsonArray = jsonObject.getJSONArray("content");

                            List<String> readIdList = new ArrayList<>();

                            for (int i = 0; i < jsonArray.size(); i++) {
                                ImMessage imMessage = imMessageRepository.findFirstByIdMessage(jsonArray.getString(i));
                                imMessage.setIsRead(1);
                                imMessageRepository.save(imMessage);

                                readIdList.add(jsonArray.getString(i));
                            }

                            //通知乘客，司机已读消息了
                            WebSocketSession driverSocket = driverList.get("sj_1");
                            if (driverSocket != null) {
                                JSONObject returnContent = new JSONObject();
                                returnContent.put("type", 3);
                                returnContent.put("orderId", orderId);
                                returnContent.put("data", readIdList);
                                driverSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                            }

                        }

                        if ("2".equals(source)) {
                            JSONArray jsonArray = jsonObject.getJSONArray("content");

                            List<String> readIdList = new ArrayList<>();

                            for (int i = 0; i < jsonArray.size(); i++) {
                                ImMessage imMessage = imMessageRepository.findFirstByIdMessage(jsonArray.getString(i));
                                imMessage.setIsRead(1);
                                imMessageRepository.save(imMessage);
                                readIdList.add(jsonArray.getString(i));
                            }

                            //通知乘客，司机已读消息了
                            WebSocketSession passengerSocket = passengerList.get("ck_1");
                            if (passengerSocket != null) {
                                JSONObject returnContent = new JSONObject();
                                returnContent.put("type", 3);
                                returnContent.put("orderId", orderId);
                                returnContent.put("data", readIdList);
                                passengerSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                            }

                        }

                    }

                    //消息发生事件
                    if (type == 99) {
                        String orderId = jsonObject.getString("orderId");
                        String content = jsonObject.getString("content");
                        Integer messageType = jsonObject.getInteger("messageType");

                        if (messageType == null) {
                            messageType = 1;
                        }

                        //乘客发送消息给司机
                        if ("1".equals(source)) {
                            //保存消息到数据库中
                            ImMessage imMessage = new ImMessage();
                            imMessage.setSource(1);
                            imMessage.setSendTime(new Date());
                            imMessage.setIsRead(0);
                            imMessage.setContent(content);
                            imMessage.setOrderId(orderId);
                            imMessage.setMessageType(messageType);
                            imMessageRepository.save(imMessage);

                            //回信息给乘客 告知发送成功了
                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 99);
                            returnContent.put("orderId", orderId);
                            returnContent.put("data", imMessage);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));

                            //推送消息给司机
                            WebSocketSession driverSocket = driverList.get("sj_1");
                            if (driverSocket != null) {
                                driverSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                            }
                        }

                        //司机发送消息给乘客
                        if ("2".equals(source)) {
                            //保存消息到数据库中
                            ImMessage imMessage = new ImMessage();
                            imMessage.setSource(2);
                            imMessage.setSendTime(new Date());
                            imMessage.setIsRead(0);
                            imMessage.setContent(content);
                            imMessage.setOrderId(orderId);
                            imMessage.setMessageType(messageType);
                            imMessageRepository.save(imMessage);

                            //回信息给司机 告知发送成功了
                            JSONObject returnContent = new JSONObject();
                            returnContent.put("type", 99);
                            returnContent.put("orderId", orderId);
                            returnContent.put("data", imMessage);
                            session.sendMessage(new TextMessage(returnContent.toJSONString()));

                            //推送消息给乘客
                            WebSocketSession passengerSocket = passengerList.get("ck_1");
                            if (passengerSocket != null) {
                                passengerSocket.sendMessage(new TextMessage(returnContent.toJSONString()));
                            }
                        }


                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(message.getPayload());
                System.out.println("Parse JSON Error");
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭后的逻辑
        Map<String, String> params = getParams(session.getUri());
        String source = params.get("source");
        String token = params.get("token");
        String userId = params.get("user_id");

        //从保存的会话中剔除出去
        if (StringUtils.isNotBlank(source) && StringUtils.isNotBlank(userId)) {
            if ("1".equals(source)) {
                passengerList.remove(userId);
            }
            if ("2".equals(source)) {
                driverList.remove(userId);
            }
        }
    }

    private Map<String, String> getParams(URI uri) {

        Map<String, String> result = new LinkedHashMap<>();

        if (uri == null) {
            return result;
        }

        String query = uri.getQuery();

        if (query != null) {
            String[] params = query.split("&");
            for (String param : params) {
                int index = param.indexOf("=");

                String key = null;
                String value = null;

                if (index > 0) {
                    key = param.substring(0, index);
                    value = param.substring(index + 1);
                }

                if (key != null) {
                    result.put(key, value);
                }
            }
        }

        return result;
    }
}
